<template>
  <div class="app-container">
    <el-card class="box-card">
      <el-row :gutter="40">
        <el-col :span="6">
          <el-input
            v-model="listQuery.name"
            placeholder="请输入内容"
            clearable
            @keyup.enter.native="handleFilter"
          >
            <el-button slot="append" icon="el-icon-search" @click.native="handleFilter"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" icon="el-icon-plus" size="medium" @click="handleAddUser">新增用户</el-button>
        </el-col>
      </el-row>
      <el-table
        :data="userList"
        border
        :key="tableKey"
        v-loading="listLoading"
        fit
        highlight-current-row
        style="width: 100%;"
      >
        <el-table-column type="index" label="#" align="center"></el-table-column>
        <el-table-column align="center" label="登录名" width="220">
          <template slot-scope="scope">{{ scope.row.name }}</template>
        </el-table-column>
        <el-table-column align="center" label="真实姓名">
          <template slot-scope="scope">{{ scope.row.real_name }}</template>
        </el-table-column>
        <el-table-column align="center" label="性  别">
          <template slot-scope="scope">{{ scope.row.gender }}</template>
        </el-table-column>
        <el-table-column align="center" label="手机号码" width="140">
          <template slot-scope="scope">{{ scope.row.telephone }}</template>
        </el-table-column>
        <el-table-column align="center" label="超级用户" width="150">
          <template slot-scope="scope">
            <el-button
              v-if="scope.row.is_superuser"
              type="success"
              size="mini"
              icon="el-icon-check"
              circle
            ></el-button>
            <el-button v-else type="danger" size="mini" icon="el-icon-close" circle></el-button>
          </template>
        </el-table-column>
        <el-table-column align="center" label="是否有效" width="150">
          <template slot-scope="scope">
            <el-button
              v-if="scope.row.is_active"
              type="success"
              size="mini"
              icon="el-icon-check"
              circle
            ></el-button>
            <el-button v-else type="danger" size="mini" icon="el-icon-close" circle></el-button>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" width="350px">
          <template slot-scope="scope">
            <el-button type="primary" size="mini" icon="el-icon-edit" @click="handleEdit(scope)"></el-button>
            <el-button type="danger"  size="mini"  icon="el-icon-delete"  @click="handleDelete(scope)"></el-button>
            <el-button  type="success"  size="mini"  icon="el-icon-setting"  @click="setRoleDialg(scope.row)">角色</el-button>
            <el-button  type="success"  size="mini"  icon="el-icon-key"  @click="handlePassword(scope.row)">密码</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="listQuery.page"
        :limit.sync="listQuery.page_size"
        @pagination="getUsers"
      />
    </el-card>
    <!-- 对话框表单 -->
    <el-dialog :visible.sync="dialogVisible" :title="dialogType==='edit'?'编辑用户':'新建用户'" width="30%">
      <el-form
        :model="userForm"
        :rules="userFormRules"
        ref="userFormRef"
        label-width="80px"
        label-position="right"
        style="width: 95%; padding:0 30px;"
      >
        <el-form-item label="登录名" prop="name">
          <el-input
            type="text"
            :disabled="dialogType=='edit'"
            v-model="userForm.name"
            placeholder="登录名"
            maxlength="30"
            show-word-limit
            clearable
          />
        </el-form-item>
        <el-form-item label="真实姓名" prop="real_name">
          <el-input
            v-model="userForm.real_name"
            placeholder="真实姓名"
            maxlength="30"
            show-word-limit
            clearable
          />
        </el-form-item>
        <el-form-item label="性  别">
          <el-select v-model="userForm.gender" placeholder="请选择性别" clearable>
            <el-option
              v-for="item in genders"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="dialogType=='new'" label="密  码" prop="password">
          <el-input v-model="userForm.password" placeholder="密 码" show-password clearable />
        </el-form-item>
        <el-form-item v-if="dialogType=='new'" label="密码确认" prop="repassword">
          <el-input v-model="userForm.repassword" placeholder="密码确认" show-password clearable />
        </el-form-item>
        <el-form-item label="手机号码" prop="telephone">
          <el-input v-model="userForm.telephone" placeholder="手机号码" clearable />
        </el-form-item>
        <el-form-item label="超级用户">
          <el-switch v-model="userForm.is_superuser"></el-switch>
        </el-form-item>
        <el-form-item label="是否有效">
          <el-switch v-model="userForm.is_active"></el-switch>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button type="danger" @click="dialogVisible=false">取消</el-button>
        <el-button type="primary" @click="SaveUser">保存</el-button>
      </div>
    </el-dialog>
    <!-- 分配角色的对话框 -->
    <el-dialog title="分配角色" :visible.sync="roleDialogVisible" width="50%">
      <div>
        <p>当前的用户：{{userForm.name}}</p>
        <p>真实姓名：{{userForm.real_name}}</p>
        <p>
          分配角色：
          <el-select v-model="userForm.roles" placeholder="请选择角色" clearable multiple>
            <el-option v-for="item in rolesList" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </p>
      </div>
      <span slot="footer">
        <el-button @click="roleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveRoleInfo">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改密码对话框 -->
    <el-dialog title="修改密码" :visible.sync="pwdDialogVisible" width="30%">
      <el-form
        :model="pwdForm"
        :rules="pwdFormRules"
        ref="pwdFormRef"
        label-width="80px"
        label-position="right"
        style="width: 95%; padding:0 30px;"
      >
        <el-form-item label="当前用户" prop="name">
          <el-input v-model="pwdForm.name" placeholder="当前用户" disabled />
        </el-form-item>
        <el-form-item label="新密码" prop="password">
          <el-input v-model="pwdForm.password" placeholder="输入新密码" show-password clearable />
        </el-form-item>
        <el-form-item label="密码确认" prop="repassword">
          <el-input v-model="pwdForm.repassword" placeholder="密码确认" show-password clearable />
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="pwdDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="changePassword">修改密码</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getUsers, addUser, updateUser, delUser, updatePasswd } from "@/api/user";
import { getRolesList } from "@/api/roles";
import Pagination from "@/components/Pagination"; // secondary package based on el-pagination

const defaultUser = {
  id: undefined,
  name: "",
  real_name: "",
  gender: "",
  password: "",
  repassword: "",
  telephone: "",
  is_superuser: false,
  is_active: true,
  roles: []
};

const defaultPwd = {
    id: null,
    name: "",
    password: "",
    repassword: ""
};

export default {
  name: "users",
  data() {
    // 验证手机号的规则
    const checkMobile = (rule, value, cb) => {
      // 验证手机号的正则表达式
      const regMobile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/;

      if (regMobile.test(value)) {
        return cb();
      }

      cb(new Error("请输入合法的手机号"));
    };

    const validatePass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入密码"));
      } else if (value.length < 6 || value.lenght > 15) {
        callback(new Error("密码长度在6~15个字符之间"));
      } else {
        if (this.userForm.repassword !== "") {
          this.$refs.userFormRef.validateField("repassword");
        }
        callback();
      }
    };
    const validatePass2 = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value !== this.userForm.password) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };

    const validatePasswd = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入密码"));
      } else if (value.length < 6 || value.lenght > 15) {
        callback(new Error("密码长度在6~15个字符之间"));
      } else {
        if (this.pwdForm.repassword !== "") {
          this.$refs.pwdFormRef.validateField("repassword");
        }
        callback();
      }
    };
    const validatePasswd2 = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value !== this.pwdForm.password) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };

    return {
      userForm: Object.assign({}, defaultUser),
      userFormRules: {
        name: [
          { required: true, message: "请输入登录名", trigger: "blur" },
          { min: 3, max: 30, message: "长度在 3 到 30 个字符", trigger: "blur" }
        ],
        real_name: [
          { required: true, message: "请输入真实姓名", trigger: "blur" },
          { min: 1, max: 30, message: "长度在 1 到 30 个字符", trigger: "blur" }
        ],
        password: [{ validator: validatePass, trigger: "blur" }],
        repassword: [{ validator: validatePass2, trigger: "blur" }],
        telephone: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" }
        ]
      },

      pwdFormRules: {
        password: [{ validator: validatePasswd, trigger: "blur" }],
        repassword: [{ validator: validatePasswd2, trigger: "blur" }],
      },

      genders: [
        {
          value: "男",
          label: "男"
        },
        {
          value: "女",
          label: "女"
        }
      ],
      dialogVisible: false,
      dialogType: "new",
      userList: [],
      tableKey: 0,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        page_size: 20,
        name: undefined
      },
      // 分配角色
      roleDialogVisible: false,
      rolesList: [],
      pwdForm: Object.assign({}, defaultPwd),
      pwdDialogVisible: false,
    };
  },
  components: {
    Pagination
  },
  created() {
    this.getUsers();
    this.getRolesList();
  },
  methods: {
    getUsers() {
      this.listLoading = true;
      getUsers(this.listQuery)
        .then(res => {
          this.total = res.count;
          this.userList = res.results;
          this.listLoading = false;
        })
        .catch(error => {
          console.log(error.message);
          this.listLoading = false;
        });
    },
    getRolesList() {
      getRolesList()
        .then(res => {
          this.rolesList = res;
        })
        .catch(error => {
          console.log(error);
          this.$message.error("获取角色列表失败!");
        });
    },
    // 查询
    handleFilter() {
      this.listQuery.page = 1;
      this.getUsers();
    },
    // 增加用户
    handleAddUser() {
      this.userForm = Object.assign({}, defaultUser);

      this.dialogType = "new";
      this.dialogVisible = true;

      this.$nextTick(() => {
        this.$refs.userFormRef.clearValidate();
      });
    },
    // 修改用户
    handleEdit(scope) {
         
      this.userForm = Object.assign({}, scope.row);
      delete this.userForm["avatar"]
      this.dialogType = "edit";

      this.dialogVisible = true;
      this.$nextTick(() => {
        this.$refs["userFormRef"].clearValidate();
      });
      console.log(this.userForm.id);
    },
    // 删除用户
    handleDelete({ $index, row }) {
      this.$confirm("确定要删除该用户吗?", "删除提示：", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          const res = await delUser(row.id);

          this.userList.splice($index, 1);
          this.$message({
            type: "success",
            message: "删除成功!"
          });
        })
        .catch(err => {
          console.error(err);
        });
    },
    // 保存操作
    async SaveUser() {
      this.$refs.userFormRef.validate(async valid => {
        if (!valid) return;

        const isEdit = this.dialogType === "edit";
        if (isEdit) {
          console.log(isEdit, this.userForm.id);
          const res = await updateUser(this.userForm);
          console.log(isEdit, res);
          const index = this.userList.findIndex(v => v.id === res.id);
          this.userList.splice(index, 1, res);
        } else {
          const res = await addUser(this.userForm);
          const { id } = res;
          if (id > 0) {
            this.getUsers();
          }
        }

        const { name, real_name } = this.userForm;

        this.dialogVisible = false;
        this.$notify({
          title: "Success",
          dangerouslyUseHTMLString: true,
          message: `
              <div>登录名: ${name}</div>
              <div>真实姓名: ${real_name}</div>
            `,
          type: "success"
        });
      });
    },
    setRoleDialg(user) {
      this.userForm = Object.assign({}, user);
      this.roleDialogVisible = true;
    },
    saveRoleInfo() {
      console.log(this.userForm)
      updateUser(this.userForm).then( res => {
        console.log(res);
        const index = this.userList.findIndex(v => v.id === res.id);
        this.userList.splice(index, 1, res);
        this.$message.success("分配权限成功!")
      }).catch( error => {
        this.$message.error("分配权限失败!")
      })
      this.roleDialogVisible = false;
    },
    handlePassword({id, name}) { 
      this.pwdForm = Object.assign({}, defaultPwd)
      this.pwdForm.id = id;
      this.pwdForm.name = name;
      this.pwdDialogVisible = true;
      
      this.$nextTick(() => {
        this.$refs.pwdFormRef.resetFields();
        this.$refs["pwdFormRef"].clearValidate();
      });
    },
    changePassword(){
      this.$refs.pwdFormRef.validate(async valid => {
        if (!valid) return;
        const res = await updatePasswd(this.pwdForm);
        console.log("return:", res);
        this.pwdDialogVisible = false;
        if(res){
          this.$message.success(res.message)
        }else{
          this.$message.success("密码修改失败!")
        }
        
        
      });
    },
  }
};
</script>

<style lang='scss' scoped>
.app-container {
  .el-table {
    margin-top: 10px;
    width: 100%;
  }
  .permission-tree {
    margin-bottom: 30px;
  }
}
</style>